package net.oschina.j2cache.autoconfigure;

import java.io.IOException;

import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.J2Cache;
import net.oschina.j2cache.J2CacheBuilder;
import net.oschina.j2cache.cache.support.util.J2cacheSpringUtil;
import net.oschina.j2cache.cache.support.util.SpringJ2CacheConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.StandardEnvironment;

/**
 * 启动入口
 * <p>
 * PropertySource: 　加载指定的属性文件（*.properties）到 Spring 的 Environment 中
 *
 * @author zhangsaizz
 */
@ConditionalOnClass(J2Cache.class)
@EnableConfigurationProperties({J2CacheConfig.class})
@Configuration
@PropertySource(value = "${j2cache.config-location}", encoding = "UTF-8", ignoreResourceNotFound = true)
public class J2CacheAutoConfiguration {

    /**
     * StandardEnvironment 他是一个Environment的一个实现，适用于非WEB的应用
     * 除了ConfigurableEnvironment通用的属性解析和profile相关的操作外，StandardEnvironment还提供了
     * system properties 和 system environment variables 两个属性
     */
    @Autowired
    private StandardEnvironment standardEnvironment;

    @Bean
    public net.oschina.j2cache.J2CacheConfig j2CacheConfig() throws IOException {
        return SpringJ2CacheConfigUtil.initFromConfig(standardEnvironment);
    }

    @Bean
    @DependsOn({"j2cacheSpringUtil", "j2CacheConfig"})
    public CacheChannel cacheChannel(net.oschina.j2cache.J2CacheConfig j2CacheConfig) throws IOException {
        J2CacheBuilder builder = J2CacheBuilder.init(j2CacheConfig);
        return builder.getChannel();
    }

    @Bean
    public J2cacheSpringUtil j2cacheSpringUtil() {
        return new J2cacheSpringUtil();
    }

}
